//
//  VedioDownloadDetailViewController.m
//  UESTCPioneer
//
//  Created by Apple on 14-5-11.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "VedioDownloadDetailViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "DirectionMPMoviePlayerViewController.h"
#import "DownloadHandler.h"
#import "AppDelegate.h"
#import "Reachability.h"
#import "PartyVedioDownloadEntity.h"
#import "Vitamio.h"
#import "PlayerController.h"
#import "PlayerControllerDelegate.h"

@interface VedioDownloadDetailViewController ()<PlayerControllerDelegate>{
    /*判断网络连接状况*/
    Reachability *hostReach;
    
    NSString * urlString;
    NSString * vedioFlag;
    /*进度条控制*/
    unsigned long long sizeDownload;//总共下载完成的
    unsigned long long sizeRecive;//本次下载完成字节数
    unsigned long long sizeTotal;//文件总大小
    //    unsigned long long total;
    /*end*/
    BOOL isDownloading;
    float fileLength;
    ASINetworkQueue * queue;
    NSTimer * timer;
    BOOL connectNet;
    BOOL finished;
    
    NSString * _vedioFilePath ;
    NSString * _vedioFileName;
}
@property (nonatomic,strong) UILabel * nameLabel;
@property (nonatomic,strong) UILabel * stateLabel;
@property (nonatomic,strong) UILabel * sizeLabel;

//下载与暂停
@property (nonatomic,strong) UIButton * downloadButton;
//在线播放
@property (nonatomic,strong) UIButton * onlinePlayButton;
//播放视频
@property (nonatomic,strong) UIButton * playButton;

//在线播放控制器
//@property (nonatomic,strong) MPMoviePlayerViewController * onlinePlayer;
@property (nonatomic,strong) DirectionMPMoviePlayerViewController * onlinePlayer;
//离线播放控制器
@property (nonatomic,strong) MPMoviePlayerViewController * offlinePlayer;

@property (nonatomic,strong) NSString * fileName;
@property (nonatomic,strong) NSString * fileDownloadPath;
@property (nonatomic,strong) NSNumber * fileTheId;
@property (nonatomic,strong) NSString * fileSize;

@property (nonatomic,strong) UIProgressView * progress;
@property (nonatomic,strong) ASIHTTPRequest * downRequest;
@property (nonatomic,strong) ASIHTTPRequest * onlineRequest;
/*最新修改*/
@property UIAlertView * alert;
/**/
@property (nonatomic, assign) IBOutlet UITextField *urlTextFidld;
@property (nonatomic, assign)          int          isPlay2;
/**/
@property (atomic, strong) NSData *partialData;
@property (atomic, strong) NSURLSessionDownloadTask *task;
@property (atomic,strong)  NSURLSession  *defaultSession;
@property (nonatomic) BOOL recordFlag;
/**/
@end

@implementation VedioDownloadDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id) initWithFileName:(NSString *)fileName URLString:(NSString *)str filePath:(NSString *)filePath theId:(NSNumber *)theId size:(NSString *)size{
    if (self) {
        _fileName = fileName;
        _vedioFileName = fileName;
        urlString = str;
        NSArray * array = [fileName componentsSeparatedByString:@"."];
        vedioFlag = [array lastObject];
//        NSLog(@"array = %@",array);
//        NSLog(@"vedioFlag = %@",vedioFlag);
        _fileDownloadPath = filePath;
        _fileTheId = theId;
        _fileSize = size;
        
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    _recordFlag = NO;
    self.title = @"视频下载";
    self.view.backgroundColor = [UIColor whiteColor];
    finished = NO;
    //    [self.playButton ]
    
    [self.view addSubview:self.downloadButton];
//    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 310, 50)];
//    _nameLabel.text = [NSString stringWithFormat:@"视频名 : %@",_fileName];
    
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 5,self.view.frame.size.width - 90, 50)];
    _nameLabel.adjustsFontSizeToFitWidth = YES;
    [_nameLabel setNumberOfLines:0];
    _nameLabel.text = _fileName;
    [_nameLabel setFont:[UIFont systemFontOfSize:15]];
    
    UILabel *fileLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 80, 50)];
    fileLabel.text = @"视频名 :";
    

    UILabel * state = [[UILabel alloc] initWithFrame:CGRectMake(5, _nameLabel.frame.origin.y + _nameLabel.frame.size.height + 10, 120, 50)];
    state.text = @"下载状态 :";
    //    _stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.progress.frame.origin.x + self.progress.frame.size.width + 5, state.frame.origin.y , 50, 50)];
    _stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.progress.frame.origin.x , state.frame.origin.y + 13, 50, 50)];
    [_stateLabel setTextColor:[UIColor grayColor]];
    [_stateLabel setFont:[UIFont fontWithName:@"Helvetica" size:10]];
    
    _sizeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.progress.frame.origin.x + self.progress.frame.size.width - 30 , state.frame.origin.y + 13, 50, 50)];
    _sizeLabel.text = self.fileSize;
    [_sizeLabel setFont:[UIFont fontWithName:@"Helvetica" size:10]];
    [_sizeLabel setTextColor:[UIColor grayColor]];
    [self.view addSubview:_sizeLabel];
    
    for (int i = 0; i < 2; i ++) {
        UIView * bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 60+60*i, 320, 1)];
        bgView.backgroundColor = [UIColor redColor];
        [self.view addSubview:bgView];
    }
    NSString* filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:filePath]) {
//        NSLog(@"视频已下载完毕!");
        finished = YES;
        [self.progress setProgress:1 animated:NO];
        [self.stateLabel setText: @"100%"];
        
        [self.view addSubview:self.playButton];
        [_downloadButton setTitle:@"删除视频" forState:UIControlStateSelected];
        [_downloadButton setTitle:@"删除视频" forState:UIControlStateNormal];
        [_downloadButton setTitle:@"删除视频" forState:UIControlStateHighlighted];
    }
    //    [self.view addSubview:self.downloadButton];
    [self.view addSubview:self.onlinePlayButton];
    [self.view addSubview:_nameLabel];
    [self.view addSubview:fileLabel];
    [self.view addSubview:_stateLabel];
    [self.view addSubview:self.progress];
    [self.view addSubview:state];
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    self.partialData = [NSData data];
    [self getDownloadSize];
    [self getDownloadRequest];
    timer =  [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(function) userInfo:nil repeats:YES];
    //每0.2秒运行一次function方法。
    //开启定时器
    [timer setFireDate:[NSDate distantPast]];
}

-(void)function{
    
    unsigned long long total;
    if (isDownloading) {
        total = sizeDownload + self.downRequest.totalBytesRead;
    }else{
        total = sizeDownload;
    }
    
    float progress;
    //    NSLog(@"sizeDownload = %llu,self.downRequest.totalBytesRead = %llu,total = %llu,sizeTotal = %llu",sizeDownload,self.downRequest.totalBytesRead,total,sizeTotal);
    //    if (sizeTotal==0 && finished == NO) {
    //        progress = 0else {
    //        progress= (total*1.0)/(sizeTotal*1.0);
    //    }
    if (sizeTotal == 0 && finished == NO) {
        progress = 0.0;
    }else if(finished == YES){
        progress =1.000000f;
    }else{
        progress= (total*1.0)/(sizeTotal*1.0);
    }
    [self.progress setProgress:progress animated:YES];
    self.stateLabel.text = [NSString stringWithFormat:@"%.0f%%",progress*100];
    if (progress == 1.000000f) {
        //        NSLog(@"progress = %f",progress);
        [self setButtonTitle];
        self.stateLabel.text = @"100%";
        
        if (!_recordFlag) {
            //向服务器端发送下载信息，便于服务器端进行统计
            [self sendToServer];
            _recordFlag = YES;
        }
    }
}

-(void)sendToServer{
    //hhttp://115.28.239.113:8080/ScienceApp/AdminRecord.do? type=video&userName=&userId=&doc_name=(utf-8编码一次)
    NSDictionary *requestData=@{@"type":@"video"
                                ,@"userId":[constant getUserId]
                                ,@"userName":[constant getUserName]
                                ,@"doc_name":[helper urlencode:_fileName]
                                };
    
    NSLog(@"requestData = %@",requestData);
    [NetworkCenter AFRequestWithRecordData:requestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
//        NSArray *arr = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
//        NSDictionary *dic =arr[0];
//        NSLog(@"返回值dic = %@",dic);
//        if ([dic[@"result"] isEqualToString:@"success"]){
//            [Alert showAlert:@"上传成功"];
//        } else {
//        }
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"网络连接出错"];
        NSLog(@"网络连接出错 = %@",error.localizedDescription);
    }];
}


-(void)viewWillDisappear:(BOOL)animated{
    
    if ([self.downloadButton.titleLabel.text isEqualToString:@"暂停下载"]) {
        //将已经下载完成的字节数添加进totalBytesRcv队列
        for (NSDictionary * dict in [self appDelegate].totalBytesRcv) {
            NSString * name = [dict objectForKey:@"name"];
            if ([name isEqualToString:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]) {
                sizeDownload = [[dict objectForKey:@"totalBytesRead"] longLongValue];
                sizeTotal = [[dict objectForKey:@"sizetotal"] longLongValue];
                [[self appDelegate].totalBytesRcv removeObject:dict];
//                NSLog(@"上次已经下载了sizeDownload = %llu",sizeDownload);
                break;
            }
        }
        if (sizeTotal <=self.downRequest.contentLength) {
            sizeTotal = self.downRequest.contentLength;
        }
        
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        [dic setObject:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag] forKey:@"name"];
        [dic setObject:[NSString stringWithFormat:@"%llu",sizeDownload]  forKey:@"totalBytesRead"];
        [dic setObject:[NSString stringWithFormat:@"%llu",sizeTotal]  forKey:@"sizetotal"];
        [[self appDelegate].totalBytesRcv addObject:dic];
        
    }
    //关闭定时器
    [timer setFireDate:[NSDate distantFuture]];
}

-(UIProgressView *)progress{
    if (!_progress) {
        self.progress= [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        [self.progress setFrame:CGRectMake(100, _nameLabel.frame.origin.y + _nameLabel.frame.size.height + 33, 185, 10)];
    }
    return _progress;
}


-(UIButton *)downloadButton{
    if (!_downloadButton) {
        //        _downloadButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 250, 100.0, 30.0)];
        _downloadButton = [[UIButton alloc] initWithFrame:CGRectMake(30, 150, 100.0, 30.0)];
        [_downloadButton setBackgroundImage:[UIImage imageNamed:@"filedl"] forState:UIControlStateNormal];
        [_downloadButton setBackgroundImage:[UIImage imageNamed:@"filedl"] forState:UIControlStateHighlighted];
        [_downloadButton setBackgroundImage:[UIImage imageNamed:@"filedl"] forState:UIControlStateSelected];
        
        
        [_downloadButton setTitle:@"下载视频" forState:UIControlStateSelected];
        [_downloadButton setTitle:@"下载视频" forState:UIControlStateNormal];
        [_downloadButton setTitle:@"下载视频" forState:UIControlStateHighlighted];
        
//        [_downloadButton.layer setCornerRadius:5.0f];
        
        [_downloadButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 30, 5, 5)];
        [_downloadButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
        _downloadButton.titleLabel.textColor = [UIColor whiteColor];
        
        [_downloadButton addTarget:self action:@selector(downloadButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _downloadButton;
}

-(UIButton *)onlinePlayButton{
    if (!_onlinePlayButton) {
        _onlinePlayButton = [[UIButton alloc] initWithFrame:CGRectMake(190, 150, 100.0, 30.0)];
        [_onlinePlayButton setBackgroundImage:[UIImage imageNamed:@"filedl"] forState:UIControlStateNormal];
        [_onlinePlayButton setBackgroundImage:[UIImage imageNamed:@"filedl"] forState:UIControlStateHighlighted];
        [_onlinePlayButton setBackgroundImage:[UIImage imageNamed:@"filedl"] forState:UIControlStateSelected];
        [_onlinePlayButton setTitle:@"在线播放" forState:UIControlStateSelected];
        [_onlinePlayButton setTitle:@"在线播放" forState:UIControlStateNormal];
        [_onlinePlayButton setTitle:@"在线播放" forState:UIControlStateHighlighted];
//        [_onlinePlayButton.layer setCornerRadius:5.0f];
        
        [_onlinePlayButton setBackgroundColor:[UIColor redColor]];
        [_onlinePlayButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 30, 5, 5)];
        [_onlinePlayButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
        _onlinePlayButton.titleLabel.textColor = [UIColor whiteColor];
        [_onlinePlayButton addTarget:self action:@selector(onlinePlayButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _onlinePlayButton;
}

-(UIButton *)playButton{
    if (!_playButton) {
        _playButton = [[UIButton alloc] initWithFrame:CGRectMake(self.progress.frame.origin.x + self.progress.frame.size.width + 5, self.progress.frame.origin.y - 12, 28.0, 28.0)];
        [_playButton setBackgroundImage:[UIImage imageNamed:@"partyvedio.png"] forState:UIControlStateNormal];
        [_playButton setBackgroundImage:[UIImage imageNamed:@"partyvedio.png"] forState:UIControlStateHighlighted];
        [_playButton setBackgroundImage:[UIImage imageNamed:@"partyvedio.png"] forState:UIControlStateSelected];
        
        [_playButton addTarget:self action:@selector(playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playButton;
}

-(void)playButtonClick:(UIButton *)btn{
    
//    NSLog(@"播放视频!");
    
    NSString * webPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Private Documents/Temp"];
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager * fileManager = [NSFileManager defaultManager ];
    if (![fileManager fileExistsAtPath:cachePath]) {
        [fileManager createDirectoryAtPath:cachePath withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
//        NSLog(@"cachePath = %@",cachePath);
    }
    
    if (![fileManager fileExistsAtPath:webPath]) {
        [fileManager createDirectoryAtPath:webPath withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
//        NSLog(@"webPath = %@",webPath);
    }
    
    if ([fileManager fileExistsAtPath:[cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]]) {
        
        _vedioFilePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]];
//        NSLog(@"_vedioFilePath = %@",_vedioFilePath);
        self.isPlay2 = NO;
        sCurrPlayIdx = 0;
        PlayerController *playerCtrl;
        playerCtrl = [[PlayerController alloc] initWithNibName:nil bundle:nil fileName:_vedioFileName];
        playerCtrl.delegate = self;
        
        
        [self presentViewController:playerCtrl animated:YES completion:^{
        }];
        
        
        
        
//        
//        MPMoviePlayerViewController * playerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:[cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]]];
//        NSLog(@"开始出现播放画面");
//        [self presentMoviePlayerViewControllerAnimated:playerViewController];
    }
}

-(void)downloadButtonClick:(UIButton *)sender{
    
    NSString * webPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Private Documents/Temp"];
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager * fileManager = [NSFileManager defaultManager ];
    if (![fileManager fileExistsAtPath:cachePath]) {
        [fileManager createDirectoryAtPath:cachePath withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
//        NSLog(@"cachePath = %@",cachePath);
    }
    
    if (![fileManager fileExistsAtPath:webPath]) {
        [fileManager createDirectoryAtPath:webPath withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
//        NSLog(@"webPath = %@",webPath);
    }
    
    if ([fileManager fileExistsAtPath:[cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]]) {
//        NSLog(@"删除视频!");
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                       message:@"确定要删除该视频吗？"
                                                      delegate:self
                                             cancelButtonTitle:@"确定"
                                             otherButtonTitles:@"取消",nil];
        
        alert.tag = 2;
        [alert show];
    }else{
        
        [self netWorkConnect];
        /********************************************************************/
        if (connectNet == NO) {
            [self.downloadButton setTitle:@"下载视频" forState:UIControlStateSelected];
            [self.downloadButton setTitle:@"下载视频" forState:UIControlStateNormal];
            [self.downloadButton setTitle:@"下载视频" forState:UIControlStateHighlighted];
            return;
        }
        /********************************************************************/
        /*设置下载*/
        if ([self.downloadButton.titleLabel.text isEqualToString:@"暂停下载"]) {
            //执行暂停操作
            [self.downRequest clearDelegatesAndCancel];
            //将已经下载完成的字节数添加进totalBytesRcv队列
            for (NSDictionary * dict in [self appDelegate].totalBytesRcv) {
                NSString * name = [dict objectForKey:@"name"];
                if ([name isEqualToString:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]) {
                    sizeDownload = [[dict objectForKey:@"totalBytesRead"] longLongValue];
                    sizeTotal = [[dict objectForKey:@"sizetotal"] longLongValue];
                    [[self appDelegate].totalBytesRcv removeObject:dict];
//                    NSLog(@"上次已经下载了sizeDownload = %llu",sizeDownload);
                    break;
                }
            }
            if (sizeTotal <=self.downRequest.contentLength) {
                sizeTotal = self.downRequest.contentLength;
            }
            
            sizeDownload +=self.downRequest.totalBytesRead;
            NSMutableDictionary * dic = [NSMutableDictionary dictionary];
            [dic setObject:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag] forKey:@"name"];
            [dic setObject:[NSString stringWithFormat:@"%llu",sizeDownload]  forKey:@"totalBytesRead"];
            [dic setObject:[NSString stringWithFormat:@"%llu",sizeTotal]  forKey:@"sizetotal"];
            [[self appDelegate].totalBytesRcv addObject:dic];
            
            
            for (ASIHTTPRequest * r in [self appDelegate].requestQueue) {
                NSString * name = [r.userInfo objectForKey:@"name"];
                if ([name isEqualToString:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]) {
                    [[self appDelegate].requestQueue removeObject:r];
                    break;
                }
            }
            
            [_downloadButton setTitle:@"下载视频" forState:UIControlStateSelected];
            [_downloadButton setTitle:@"下载视频" forState:UIControlStateNormal];
            [_downloadButton setTitle:@"下载视频" forState:UIControlStateHighlighted];
            isDownloading = NO;
            return;
        }
        isDownloading = YES;
        
        
        NSString * filePath =[NSString stringWithFormat:@"%@%@",baseUrl,self.fileDownloadPath];
//        NSLog(@"filePath = %@",filePath);
        
        NSURL  *url = [NSURL URLWithString:[filePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        ASIHTTPRequest * request = [[ASIHTTPRequest alloc] initWithURL:url];
        request.delegate = self;
        //检查当前网络是否可用
        
        self.fileName = [NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag];
        
        //设置超时时间
        [request setTimeOutSeconds:8];
        //下载完存储目录
        [request setDownloadDestinationPath:[cachePath stringByAppendingPathComponent:self.fileName]];
//        NSLog(@"下载完存储目录= %@",[cachePath stringByAppendingPathComponent:self.fileName]);
        //设置进度代理
        //        request.downloadProgressDelegate = self.progress;
        //临时存储目录
        [request setTemporaryFileDownloadPath:[webPath stringByAppendingPathComponent:self.fileName]];
//        NSLog(@"临时存储目录 = %@",[webPath stringByAppendingPathComponent:self.fileName]);
        //断点续载
        [request setAllowResumeForFileDownloads:YES];
//        [request setShouldAttemptPersistentConnection:NO];
        [request startAsynchronous];
        
        request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:self.fileName, @"name", nil];//为每一个下载请求即下载任务命名，以唯一确认该请求
        
        NSLog(@"request.totalBytesRead = %@",[NSString stringWithFormat:@"%llu",request.totalBytesRead ]);
        
        [[self appDelegate].requestQueue addObject:request];
        
        self.downRequest = request;
        
        [_downloadButton setTitle:@"暂停下载" forState:UIControlStateSelected];
        [_downloadButton setTitle:@"暂停下载" forState:UIControlStateNormal];
        [_downloadButton setTitle:@"暂停下载" forState:UIControlStateHighlighted];
    }
}

-(void)setButtonTitle{
    finished = YES;
    [self.view addSubview:self.playButton];
    
    [_downloadButton setBackgroundColor:[UIColor yellowColor]];
    [_downloadButton setTitle:@"删除视频" forState:UIControlStateSelected];
    [_downloadButton setTitle:@"删除视频" forState:UIControlStateNormal];
    [_downloadButton setTitle:@"删除视频" forState:UIControlStateHighlighted];
    self.stateLabel.text = @"100%";
    
}

- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
    if (fileLength == 0) {
        fileLength = request.contentLength/1024.0/1024.0;
        if (sizeTotal<=request.contentLength) {
            sizeTotal = request.contentLength;
            NSLog(@"request.contentLength = %llu",request.contentLength);
        }
    }
    
}
- (void)requestFinished:(ASIHTTPRequest *)request{
//    NSLog(@"视频下载完成!");
    finished = YES;
    [self.view addSubview:self.playButton];
    
    [_downloadButton setBackgroundColor:[UIColor yellowColor]];
    [_downloadButton setTitle:@"删除视频" forState:UIControlStateSelected];
    [_downloadButton setTitle:@"删除视频" forState:UIControlStateNormal];
    [_downloadButton setTitle:@"删除视频" forState:UIControlStateHighlighted];
    self.stateLabel.text = @"100%";
    for (ASIHTTPRequest * r in [self appDelegate].requestQueue) {
        NSString * name = [r.userInfo objectForKey:@"name"];
        if ([name isEqualToString:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]) {
            [[self appDelegate].requestQueue removeObject:r];
//            NSLog(@"已经移除了网络请求连接!");
            break;
        }
    }
    
    [self changeStatusType:1];
}

/*add 2014.05.10*/
#pragma mark  获得已经下载的文件大小
-(void)getDownloadSize{
    for (NSDictionary * dict in [self appDelegate].totalBytesRcv) {
        NSString * name = [dict objectForKey:@"name"];
        if ([name isEqualToString:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]) {
            sizeDownload = [[dict objectForKey:@"totalBytesRead"] longLongValue];
            sizeTotal = [[dict objectForKey:@"sizetotal"] longLongValue];
//            NSLog(@"name = %@,sizeTotal = %llu,sizeDownload = %llu",name,sizeTotal,sizeDownload);
            break;
        }
    }
}

#pragma mark 获得正在下载ASIHTTPRequest
-(void)getDownloadRequest{
    for ( ASIHTTPRequest * r in [self appDelegate].requestQueue) {
        NSString * name = [r.userInfo objectForKey:@"name"];
        if ([name isEqualToString:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]) {
            self.downRequest = r;
//            NSLog(@"将button更新为暂停!");
            //将button更新为暂停
            [self.downloadButton setTitle:@"暂停下载" forState:UIControlStateSelected];
            [self.downloadButton setTitle:@"暂停下载" forState:UIControlStateNormal];
            [self.downloadButton setTitle:@"暂停下载" forState:UIControlStateHighlighted];
            isDownloading = YES;
            break;
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    NSLog(@"%@",alertView.description);
//    NSString* msg = [[NSString alloc] initWithFormat:@"您按下的第%ld个按钮！",buttonIndex];
//    NSLog(@"msg = %@",msg);
    
    if (alertView.tag == 2) {
        if (buttonIndex == 1) {
            return;
        }else if(buttonIndex == 0){
            isPlay = YES;
            
            NSString* filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",_fileTheId,vedioFlag]];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            
            if ([fileManager fileExistsAtPath:filePath]) {//下载完成之后删除视频
                [self.progress setProgress:0 animated:NO];
                [self.stateLabel setText: @"%0"];
                [fileManager removeItemAtPath:filePath error:nil];
                
                [self.downloadButton setTitle:@"下载视频" forState:UIControlStateSelected];
                [self.downloadButton setTitle:@"下载视频" forState:UIControlStateNormal];
                [self.downloadButton setTitle:@"下载视频" forState:UIControlStateHighlighted];
                isDownloading = NO;
                [Alert showAlert:@"已经删除了视频!"];
                finished = NO;
                
                /******/
                [self.downRequest clearDelegatesAndCancel];
                //将已经下载完成的字节数添加进totalBytesRcv队列
                for (NSDictionary * dict in [self appDelegate].totalBytesRcv) {
                    NSString * name = [dict objectForKey:@"name"];
                    if ([name isEqualToString:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]) {
                        [[self appDelegate].totalBytesRcv removeObject:dict];
                        break;
                        }
                    }
                
                    for (ASIHTTPRequest * r in [self appDelegate].requestQueue) {
                        NSString * name = [r.userInfo objectForKey:@"name"];
                        if ([name isEqualToString:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]) {
                            [[self appDelegate].requestQueue removeObject:r];
                            break;
                        }
                    }
            
                    [_downloadButton setTitle:@"下载视频" forState:UIControlStateSelected];
                    [_downloadButton setTitle:@"下载视频" forState:UIControlStateNormal];
                    [_downloadButton setTitle:@"下载视频" forState:UIControlStateHighlighted];
                    isDownloading = NO;
                
                sizeDownload = 0;
                
                /******/
                [self.playButton removeFromSuperview];
                [self changeStatusType:2];
            }
        }
    }else if(alertView.tag == 3){
        connectNet = NO;
        
    }else if(alertView.tag == 4 ){
        
        if (buttonIndex == 1) {
//            NSLog(@"确认下载!");
            connectNet = YES;
        }else{
//            NSLog(@"取消下载!");
            connectNet = NO;
        }
    }
}

-(void) movieFinishedCallback:(NSNotification *) aNotification {
    MPMoviePlayerController * player = [aNotification object];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerPlaybackDidFinishNotification
                                                  object:player];
    [player stop];
    //[self.view removeFromSuperview];
//    NSLog(@"播放结束!");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//取得当前程序的委托
-(AppDelegate *)appDelegate{
    return (AppDelegate *) [[UIApplication sharedApplication] delegate];
}

-(void)netWorkConnect{
//    NSLog(@"进行网络连接测试!");
    NSString* result;
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    switch ([reach currentReachabilityStatus])
    {
        case NotReachable:    // 没有网络连接
        {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                             message:@"没有可用网络，请确认网络连接!"
                                                            delegate:self
                                                   cancelButtonTitle:@"确定"
                                                   otherButtonTitles: nil];
            alert.tag = 3;
            connectNet = NO;
            [alert show];
        }
            break;
        case ReachableViaWWAN:// 3G
        {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                             message:@"您现在处于3G网络下,确认下载？"
                                                            delegate:self
                                                   cancelButtonTitle:@"下载"
                                                   otherButtonTitles:@"取消",nil];
            alert.tag = 4;
            
            [alert show];
        }
            break;
            
        case ReachableViaWiFi:// WiFi
        {
            result = @"WIFI";
            connectNet = YES;
        }
            break;
    }
//    NSLog(@"result = %@",result);
}

#pragma mark 在线播放
-(void)onlinePlayButton1:(UIButton *)button{
    
    if (self.onlineRequest) {
        [self.onlineRequest clearDelegatesAndCancel];
        isPlay = NO;
        Recordull = 0;
        self.onlineRequest = nil;
    }
    
    NSString * webPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"onlineTemp"];
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager * fileManager = [NSFileManager defaultManager ];
    if (![fileManager fileExistsAtPath:cachePath]) {
        [fileManager createDirectoryAtPath:cachePath withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
//        NSLog(@"cachePath = %@",cachePath);
    }
    
    if (![fileManager fileExistsAtPath:webPath]) {
        [fileManager createDirectoryAtPath:webPath withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
//        NSLog(@"webPath = %@",webPath);
    }
    
    [self netWorkConnect];
    /********************************************************************/
    //检查当前网络是否可用
    if (connectNet == NO) {
        [self.downloadButton setTitle:@"下载视频" forState:UIControlStateSelected];
        [self.downloadButton setTitle:@"下载视频" forState:UIControlStateNormal];
        [self.downloadButton setTitle:@"下载视频" forState:UIControlStateHighlighted];
        return;
    }
    /********************************************************************/
    NSString * filePath =[NSString stringWithFormat:@"%@%@",baseUrl,self.fileDownloadPath];
    NSURL  *url = [NSURL URLWithString:[filePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    ASIHTTPRequest * request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    
    self.fileName = [NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag];
    //设置超时时间
    [request setTimeOutSeconds:8];
    //下载完存储目录
    [request setDownloadDestinationPath:[cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"/online/%@.%@",self.fileTheId,vedioFlag]]];
    NSLog(@"下载完存储目录= %@",[cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"/online/%@.%@",self.fileTheId,vedioFlag]]);
    //临时存储目录
    [request setTemporaryFileDownloadPath:[webPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]];
    NSLog(@"临时存储目录 = %@",[webPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]]);
    //断点续载，如果每次播放完成将缓冲文件删除，就没有断点续传的必要了
    //    [request setAllowResumeForFileDownloads:YES];
    [request startAsynchronous];
    
    self.onlineRequest = request;
    /*最新修改*/
    self.alert = [[UIAlertView alloc]initWithTitle:nil message:@"加载中..."  delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [self.alert show];
    /**/
    [request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total) {//当接收到字节数据时触发。
        
        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setDouble:total forKey:@"file_length"];
        Recordull +=size;//Recordull全局变量，记录已下载的文件的大小
        NSLog(@"Recordull = %llu,isPlay = %d",Recordull,isPlay);
        if (!isPlay && Recordull >400000) {
            isPlay = !isPlay;
            [self playVideo];
            
        }
    }];
    //    }
}
-(void)playVideo{
    NSString * playFile = [NSString stringWithFormat:@"http://127.0.0.1:12345/%@",[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]];
    
//    NSLog(@"playFile = %@",playFile);
//    DirectionMPMoviePlayerViewController * playerViewController = [[DirectionMPMoviePlayerViewController alloc] initWithContentURL:[NSURL  URLWithString:playFile]];
    DirectionMPMoviePlayerViewController * playerViewController = [[DirectionMPMoviePlayerViewController alloc] initWithContentURL:[NSURL  fileURLWithPath:playFile]];
    self.onlinePlayer = playerViewController;
    [[NSNotificationCenter defaultCenter]  addObserver:self
                                              selector:@selector(videoHasFinishedPlaying:)
                                                  name:MPMoviePlayerPlaybackDidFinishNotification
                                                object:self.onlinePlayer.moviePlayer];
    //    [[NSNotificationCenter defaultCenter] addObserver:self
    //                                             selector:@selector(playbackStateChanged)
    //                                                 name:MPMoviePlayerPlaybackStateDidChangeNotification
    //                                               object:self.onlinePlayer.moviePlayer];
    
    
    //    playerViewController.moviePlayer.controlStyle = MPMovieControlStyleNone;
    //    [playerViewController.moviePlayer setFullscreen:YES animated:YES];
    //    playerViewController.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
    //定义视频横屏播放
    //    [[playerViewController view] setTransform:CGAffineTransformMakeRotation(M_PI / 2)];
    //    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
    
    
//    playerViewController.view.frame = self.view.frame;//全屏播放（全屏播放不可缺）
    //    playerViewController.moviePlayer.scalingMode = MPMovieScalingModeAspectFill;//全屏播放（全屏播放不可缺）
    
    playerViewController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    
    [playerViewController.moviePlayer prepareToPlay];
    
    //在当前view上添加视频的视图
    //    [[[UIApplication sharedApplication] keyWindow] addSubview:playerViewController.view];
    
    /*最新修改*/
    [self.alert dismissWithClickedButtonIndex:0 animated:YES];
    /**/
    [self presentMoviePlayerViewControllerAnimated:playerViewController];
    [playerViewController.moviePlayer play];
}
/*
 -(void)playVideo{
 NSString * playFile = [NSString stringWithFormat:@"http://127.0.0.1:12345/%@",[NSString stringWithFormat:@"%@.%@",self.fileTheId,vedioFlag]];
 
 NSLog(@"playFile = %@",playFile);
 MPMoviePlayerViewController * playerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL  URLWithString:playFile]];
 self.onlinePlayer = playerViewController;
 [[NSNotificationCenter defaultCenter]  addObserver:self
 selector:@selector(videoHasFinishedPlaying:)
 name:MPMoviePlayerPlaybackDidFinishNotification
 object:self.onlinePlayer.moviePlayer];
 //    [[NSNotificationCenter defaultCenter] addObserver:self
 //                                             selector:@selector(playbackStateChanged)
 //                                                 name:MPMoviePlayerPlaybackStateDidChangeNotification
 //                                               object:self.onlinePlayer.moviePlayer];
 
 
 //    playerViewController.moviePlayer.controlStyle = MPMovieControlStyleNone;
 [playerViewController.moviePlayer setFullscreen:YES animated:YES];
 //    playerViewController.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
 
 playerViewController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
 
 [playerViewController.moviePlayer prepareToPlay];
 
 [self presentMoviePlayerViewControllerAnimated:playerViewController];
 
 }
 */

- (void) playbackStateChanged {
//    NSLog(@"状态发生变更!");
    MPMoviePlaybackState playbackState = [self.onlinePlayer.moviePlayer playbackState];
    switch (playbackState) {
        case MPMoviePlaybackStateStopped:
//            NSLog(@"停止");
            break;
            
        case MPMoviePlaybackStatePlaying:
//            NSLog(@"播放中");
            break;
            
        case MPMoviePlaybackStatePaused:
//            NSLog(@"暫停");
            break;
            
        case MPMoviePlaybackStateInterrupted:
//            NSLog(@"播放被中斷");
            break;
            
        case MPMoviePlaybackStateSeekingForward:
//            NSLog(@"往前快轉");
            break;
            
        case MPMoviePlaybackStateSeekingBackward:
//            NSLog(@"往後快轉");
            break;
            
        default:
//            NSLog(@"無法辨識的狀態");
            break;
    }
}

#pragma mark
- (void)videoHasFinishedPlaying:(NSNotification *)paramNotification{
    
//    NSLog(@"播放结束!");
    /* Find out what the reason was for the player to stop */
    NSNumber *reason =
    [paramNotification.userInfo
     valueForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
    if (reason != nil){
        NSInteger reasonAsInteger = [reason integerValue];
        switch (reasonAsInteger){
            case MPMovieFinishReasonPlaybackEnded:{
                /* The movie ended normally */
                self.onlineRequest = nil;
//                NSLog(@"正常结束!:MPMovieFinishReasonPlaybackEnded");
                break; }
            case MPMovieFinishReasonPlaybackError:{
                /* An error happened and the movie ended */
//                NSLog(@"播放出错，导致退出播放器!:MPMovieFinishReasonPlaybackError");
//                break; 因为播放出错退出播放器和用户主动退出播放器处理方式相同
            }
            case MPMovieFinishReasonUserExited:{
                /* The user exited the player */
//                NSLog(@"用户退出了视频播放器!");
                if (isPlay) {
//                    NSLog(@"退出在线播放!");
                    //                    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO];
                    //                    [self.onlinePlayer.moviePlayer stop];
                    //                    [self.onlinePlayer.view removeFromSuperview];
                    isPlay = NO;
                    //执行暂停操作
                    [self.onlineRequest clearDelegatesAndCancel];
                    Recordull = 0;
                    self.onlineRequest = nil;
                    
                    //删除在线播放过程中产生的临时文件
                    NSString* filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"/online/%@.%@",_fileTheId,vedioFlag]];
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    
                    if ([fileManager fileExistsAtPath:filePath]) {//下载完成之后删除视频
                        [self.progress setProgress:0 animated:NO];
                        [self.stateLabel setText: @"%0"];
                        [fileManager removeItemAtPath:filePath error:nil];
                        
                        //                        [Alert showAlert:@"已经删除了在线缓冲视频!"];
                    }else{
                        //下载过程当中删除视频
//                        NSLog(@"下载过程当中删除视频");
                        
                        NSString * filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"onlineTemp"];
                        filePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",_fileTheId,vedioFlag]];
//                        NSLog(@"filePath = %@",filePath);
                        NSFileManager *fileManager = [NSFileManager defaultManager];
                        if ([fileManager fileExistsAtPath:filePath]) {
                            [self.progress setProgress:0 animated:NO];
                            [self.stateLabel setText: @"0%"];
                            [fileManager removeItemAtPath:filePath error:nil];
                            
                            //                            [Alert showAlert:@"已经删除了在线缓冲视频!"];
                        }
                    }
                }
                break;
            }
        }
//        NSLog(@"Finish Reason = %ld", (long)reasonAsInteger);
    } /* if (reason != nil){ */
}

#pragma mark downLoadFinishDelegate

-(void)downLoadFinishWithIndexPath:(NSIndexPath *)indexPath{


}

/*最新添加*/
-(void)changeStatusType:(NSInteger)type{
//    NSLog(@"改变视频文件的下载状态!");
    NSArray * array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * filePath =[array[0] stringByAppendingPathComponent:@"downloadvedio.plist"];
    NSFileManager * fileManager = [NSFileManager defaultManager ];
     NSNumber *status ;
    if (![fileManager fileExistsAtPath:filePath]) {//不存在就创建
        NSMutableArray * array = [NSMutableArray array];
        [array addObject:[NSString stringWithFormat:@"%@",_fileTheId]];
        [array writeToFile:filePath atomically:YES];
        if (type == 1) {
            status = @1;
        }
        if (type == 2) {
            status = @2;
        }
//        NSLog(@"视频文件下载列表已经创建!");
    }else{//存在 -- 添加或删除
        NSMutableArray * array = [NSMutableArray arrayWithContentsOfFile:filePath];
        if (type == 1) {//添加
//            NSLog(@"新下载完成视频!");
            [array addObject:[NSString stringWithFormat:@"%@",_fileTheId]];
            status = @1;
        }else if (type == 2){//删除
//            NSLog(@"新删除视频!");
            [array removeObject:[NSString stringWithFormat:@"%@",_fileTheId]];
            status = @2;
        }
        [fileManager removeItemAtPath:filePath error:nil];
        [array writeToFile:filePath atomically:YES];
    }
    [self.downLoadFinishDelegate downLoadFinishWithIndexPath:status fileTheId:_fileTheId];
//    NSLog(@"下载完成文件目录:%@",[NSArray arrayWithContentsOfFile:filePath]);
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    self.downLoadFinishDelegate = segue.sourceViewController;
}
/**/
/*保留变量*/
static NSString *sMediaURLs[] = {
    @"http://115.28.239.113:8080/ScienceApp/studyDownload/video/微型党课视频01.mp4"
};

static int sCurrPlayIdx;


-(void)onlinePlayButton:(UIButton *)button
{
    
    _vedioFilePath = [NSString stringWithFormat:@"%@%@",baseUrl,self.fileDownloadPath];
    self.isPlay2 = NO;
	sCurrPlayIdx = 0;
	PlayerController *playerCtrl;
	playerCtrl = [[PlayerController alloc] initWithNibName:nil bundle:nil fileName:self.fileName];
	playerCtrl.delegate = self;
    
    
    [self presentViewController:playerCtrl animated:YES completion:^{
    }];
}

#pragma mark - PlayerControllerDelegate
- (NSURL *)playCtrlGetCurrMediaTitle:(NSString **)title lastPlayPos:(long *)lastPlayPos
{
//    NSString * filePath = [NSString stringWithFormat:@"%@%@",baseUrl,self.fileDownloadPath];
    
    NSURL  *url = [NSURL URLWithString:[_vedioFilePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
	if (self.isPlay2) {
        return url;
	}
    return url;
}

/*保留函数*/
- (NSURL *)playCtrlGetNextMediaTitle:(NSString **)title lastPlayPos:(long *)lastPlayPos
{
	int num = sizeof(sMediaURLs) / sizeof(sMediaURLs[0]);
	sCurrPlayIdx = (sCurrPlayIdx + num + 1) % num;
	NSString *v = sMediaURLs[sCurrPlayIdx];
	return [NSURL URLWithString:[v stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}

- (NSURL *)playCtrlGetPrevMediaTitle:(NSString **)title lastPlayPos:(long *)lastPlayPos
{
	int num = sizeof(sMediaURLs) / sizeof(sMediaURLs[0]);
	sCurrPlayIdx = (sCurrPlayIdx + num - 1) % num;
	NSString *v = sMediaURLs[sCurrPlayIdx];
    
	return [NSURL URLWithString:[v stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
/*保留*/

@end

